package com.lambkit.module.upms.common;

import cn.hutool.extra.mail.MailUtil;
import com.jfinal.kit.JavaKeyword;
import com.jfinal.kit.StrKit;
import com.jfinal.template.Engine;
import com.jfinal.template.source.FileSourceFactory;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class UpmsMail {

    private Engine engine;
    /**
     * 针对 Model 中七种可以自动转换类型的 getter 方法，调用其具有确定类型返回值的 getter 方法
     * 享用自动类型转换的便利性，例如 getInt(String)、getStr(String)
     * 其它方法使用泛型返回值方法： get(String)
     * 注意：jfinal 3.2 及以上版本 Model 中的六种 getter 方法才具有类型转换功能
     */
    @SuppressWarnings("serial")
    protected Map<String, String> getterTypeMap = new HashMap<String, String>() {{
        put("java.lang.String", "getStr");
        put("java.lang.Integer", "getInt");
        put("java.lang.Long", "getLong");
        put("java.lang.Double", "getDouble");
        put("java.lang.Float", "getFloat");
        put("java.lang.Short", "getShort");
        put("java.lang.Byte", "getByte");
    }};

    public UpmsMail() {
        engine = Engine.create("forGenerator");
        engine.setSourceFactory(new FileSourceFactory());
        engine.addSharedMethod(new StrKit());
        engine.addSharedObject("getterTypeMap", getterTypeMap);
        engine.addSharedObject("javaKeyword", JavaKeyword.me);
    }

    public String sendTemplate(String to, String subject, String templateFilePath, Map<String, Object> data, boolean isHtml) {
        String content = engine.getTemplate(templateFilePath).renderToString(data);
        return MailUtil.send(to, subject, content, isHtml);
    }

    public String sendTemplate(String to, String subject, String templateFilePath, Map<String, Object> data, boolean isHtml, File... files) {
        String content = engine.getTemplate(templateFilePath).renderToString(data);
        return MailUtil.send(to, subject, content, isHtml, files);
    }
}
